<?php
class User_model extends CI_Model {
    public function __construct() {
        parent::__construct();
        $this->load->database();
    }
    
    public function login($account) {
        if ( !isset($account['password']) ) {
            return FALSE;
        }
        
        if( isset($account['email']) ) {
            $query = $this->db->get_where('user', array('email' => $account['email']));
        }
        else if ( isset($account['user_id']) ) {
            $query = $this->db->get_where('user', array('user_id' => $account['user_id']));
        }
        else {
            return FALSE;
        }
        
        $row = $query->row_array();
        if (md5($account['password'] . $row['salt']) === $row['password']) {
            return TRUE;
        } else {
            return FALSE;
        }        
    }
    
    // 每一个账号邮箱唯一
    public function exist($email) {
        $query = $this->db->get_where('user', array('email' => $email));
        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    public function insert($account) {
        $account['user_id'] = $this->get_new_user_id();
        $this->db->insert('user', $account);
        $res = $this->db->affected_rows();
        if ($res > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
        
    /*
     * 用于Session中存储的用户信息
     * 
     */        
    public function getUserInfo($email) {
        $query = $this->db->get_where('user', array('email' => $email));
        $row = $query->row_array();
        return array(
            "user_id" => $row['user_id'],
            "email" => $row['email'],
            "nickname" => $row['nickname'],
            "email_verified" => $row['email_verified'],
            "gender" =>$row['gender'],
        );
    }
    
    /*
     * 用于Session中存储的用户信息，使用userid来检索
     * 
     */        
    public function getUserInfoById($user_id) {
        $query = $this->db->get_where('user', array('user_id' => $user_id));
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            return array(
                "user_id" => $row['user_id'],
                "email" => $row['email'],
                "nickname" => $row['nickname'],
                "email_verified" => $row['email_verified'],
                "gender" =>$row['gender'],
            );
        } else {
            return NULL;
        }
    }
    
    /*
     * 生成验证用户邮箱用的验证Hash值，验证时同样会使用这个函数
     * 
     */
    public function getVerifyEmailHash($email) {
        $query = $this->db->get_where('user', array('email' => $email));
        $row = $query->row_array();
        return md5($row['user_id'].$row['email'].$row['reg_time'].$row['salt']);          
    }
    
    /*
     * 生成验证用户邮箱用的验证Hash值，验证时同样会使用这个函数，使用userid来检索
     * 
     */
    public function getVerifyEmailHashById($user_id) {
        $query = $this->db->get_where('user', array('user_id' => $user_id));
        $row = $query->row_array();
        return md5($row['user_id'].$row['email'].$row['reg_time'].$row['salt']);          
    }
    
    /*
     * 修改邮箱验证位以激活或者反激活用户账户
     * 
     */
    public function setEmailVerifyFlag($user_id, $flag) {
        $this->db->update('user', array('email_verified' => $flag), array('user_id' => $user_id));
    }
    
    /*
     * 通用函数，更新特定userid的特定字段信息
     * 
     */
    public function update($user_id, $field_to_update, $value_to_update) {
        $this->db->update('user', array($field_to_update => $value_to_update), array('user_id' => $user_id));
    }
    
    /*
     * 刷新Session中保存的用户数据
     *
     */
    public function refresh_session() {
        if (isset($_SESSION['userinfo'])) {
            $userinfo = $this->getUserInfo($_SESSION['userinfo']['email']);
            $newdata = array(
                    'userinfo' => $userinfo
            );
            $this->session->unset_userdata('userinfo');
            $this->session->set_userdata($newdata);
        }
    }
    
    /*
     * 慎用，直接将session中用户刷新为指定id号用户的数据
     *
     */
    public function refresh_session_with_user_id($user_id) {        
        $userinfo = $this->getUserInfoById($user_id);
        $newdata = array(
                'userinfo' => $userinfo
        );
        $this->session->unset_userdata('userinfo');
        $this->session->set_userdata($newdata);
    }
    
    public function update_password($user_id, $newpassword, $newsalt) {
        $this->db->update('user', array(
                'password' => $newpassword,
                'salt' => $newsalt
                ), array('user_id' => $user_id));
    }
    
    /*
     * 获得一个新的用户ID，在此处设定需要预留的ID号，现在暂时遇到最后两位是叠号则跳过（再取一次）
     *
     */
    public function get_new_user_id() {
        $sql = "INSERT INTO `user_id_seq` (`id_seq`) VALUES (NULL);"; 
        $this->db->query($sql);
        $new_id = mysql_insert_id();
        
        $new_id_str = strval($new_id);
        $new_id_len = strlen($new_id_str);
        if ( $new_id_str[$new_id_len-1] == $new_id_str[$new_id_len-2])    //最后两位是叠号
            return $this->get_new_user_id();    //递归再调用一次
        else
            return $new_id;
    }
    
    public function update_optional_info($user_id, $info) {
         $query = $this->db->get_where('user_optional_info', array('user_id' => $user_id));
         if ($query->num_rows() > 0) {
             $this->db->update('user_optional_info', array(
                 'year_of_birth' => $info['year_of_birth'],
                 'living_place' => $info['living_place'],
                 'constel' => $info['constel'],
                 'is_single' => $info['is_single'],
                 'biography' => $info['biography'],
				 'email_show' => $info['email_show'],
                 'qq_show' => $info['qq_show']
                 ), array('user_id' => $user_id));
         }
         else {
             $this->db->insert('user_optional_info', array(
                 'user_id' => $user_id,
                 'year_of_birth' => $info['year_of_birth'],
                 'living_place' => $info['living_place'],
                 'constel' => $info['constel'],
                 'is_single' => $info['is_single'],
                 'biography' => $info['biography'],
				 'email_show' => $info['email_show'],
                 'qq_show' => $info['qq_show']
                 ));
         }   
    }
    
    public function get_optional_info($user_id) {
        $query = $this->db->get_where('user_optional_info', array('user_id' => $user_id));
        if ($query->num_rows() > 0) {
            return $query->row_array();
        }
        else
            return NULL;
    }
    
    public function check_optional_info($user_id) {
        $query = $this->db->get_where('user_optional_info', array('user_id' => $user_id));
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            if(''.$row['year_of_birth'].$row['living_place'].$row['constel']
                    .$row['is_single'].$row['biography'].$row['email_show']
                    .$row['qq_show'] == '' ) {
                return FALSE;
            }
            if(''.$row['year_of_birth'].$row['living_place'].$row['constel']
                    .$row['is_single'].$row['biography'].$row['email_show']
                    .$row['qq_show'] == '00' ) {
                return FALSE;
            }
            return TRUE;
        }
        else
            return FALSE;
    }
    
    /*
     * 获取用户所有的资料
     * 性别、出生年月、现居地、星座、是否单身、自述等等
     */
    public function get_user_info($user_id) {
        // TODO: 将gender挪到user_optional_info里？
        
        $query = $this->db->get_where('user_optional_info', array('user_id' => $user_id));
        if ($query->num_rows() == 0) {
            $this->db->insert('user_optional_info', array(
                 'user_id' => $user_id,
                 'year_of_birth' => NULL,
                 'living_place' => NULL,
                 'constel' => NULL,
                 'is_single' => NULL,
                 'biography' => NULL,
				 'email_show' => NULL,
                 'qq_show' => NULL
                 )
            );
        }
        
        $this->db->from('user');
        $this->db->join('user_optional_info', 'user.user_id = user_optional_info.user_id');
        $this->db->where('user.user_id', $user_id);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            return NULL;
        }        
    }
    
    public function is_admin($user_id) {
        $this->db->from('user');
        $this->db->where('user_id', $user_id);
        $this->db->where('is_admin', true);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}
?>